package com.qiudaozhang.loveblog.service.impl;

import com.qiudaozhang.loveblog.entity.Article;
import com.qiudaozhang.loveblog.entity.Tag;
import com.qiudaozhang.loveblog.repository.ArticleRepository;
import com.qiudaozhang.loveblog.repository.TagRepository;
import com.qiudaozhang.loveblog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 邱道长
 * 2019/11/13
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleRepository ar;

    @Resource
    private TagRepository tr;

//    @Transactional(rollbackOn = Exception.class)
    @Override
    public void post(Article article) {
        article.setCreated(LocalDateTime.now());//处理编写时间
        // 处理所有的tag
        Set<Tag> tagSet = processTags(article.getTags());
        article.setTags(tagSet);
        // 处理摘要
        processSummary(article);
        ar.save(article);
    }


    /**
     * 处理摘要
     * @param article
     */
    private void processSummary(Article article) {

        if(article.getContent().length() > 50) {
            article.setSummary(article.getContent().substring(0,50));
        } else {
            article.setSummary(article.getContent());
        }
    }

    private Set<Tag> processTags(Set<Tag> tags) {
        Set<Tag> tagSet = new HashSet<>();
        for (Tag t : tags) {
            Tag temp = tr.findByName(t.getName());

            if (temp == null) {
                tr.save(t);
                tagSet.add(t);
            } else {
                tagSet.add(temp);
            }
        }
        return tagSet;
    }

    @Override
    public Article findById(Long id) {
        return ar.findById(id).get();
    }

    @Override
    public void update(Article article) {
        ar.save(article);
    }
}
